<template>
  <!-- 下单页 -->
  <view>
    <u-navbar title="确认订单" :autoBack="true" :placeholder="true" bgColor="#F8F9FE"></u-navbar>
    <!-- 地址 -->
    <template v-if="server_type === 2">
      <!-- 自提：显示店铺地址 -->
      <view class="cityCard card">
        <view class="cityCard-center">
          <view class="u-line-1">
            <image src="http://qiniu.suboshimuying.cn/static/order/ic_loc2@2x.png" mode=""></image>
            {{ orderData.goodslist[0].merchant_address }}
          </view>
        </view>
      </view>
    </template>
    <template v-else>
      <!-- 送货上门：显示自己地址 -->
      <template v-if="defaultRess.area">
        <view class="cityCard card" @click="ressClick">
          <view class="cityCard-center">
            <view class="u-line-1">
              <image src="http://qiniu.suboshimuying.cn/static/order/ic_loc2@2x.png" mode=""></image>
              {{ defaultRess.area }}&nbsp;&nbsp;{{ defaultRess.address }}
            </view>
            <view class="u-line-1" style="padding-left: 50rpx; font-size: 24rpx; color: rgba(0, 0, 0, 0.55)">{{ defaultRess.name }}&nbsp;{{ defaultRess.mobile }}</view>
          </view>
          <image style="width: 16rpx" src="http://qiniu.suboshimuying.cn/static/order/ic-arrow-more@2x.png" mode=""></image>
        </view>
      </template>
      <template v-else>
        <view class="cityCard card" @click="ressClick">
          暂无地址
          <image style="width: 16rpx" src="http://qiniu.suboshimuying.cn/static/order/ic-arrow-more@2x.png" mode=""></image>
        </view>
      </template>
    </template>

    <!-- 订单信息 -->
    <view class="goodCard card" v-for="(item, index) in orderData.goodslist" :key="index">
      <view class="goodCard-title">
        <image src="http://qiniu.suboshimuying.cn/static/order/ic-shop@2x.png" mode=""></image>
        <text>{{ item.merchant_name }}</text>
      </view>
      <view class="goodCard-main">
        <image class="mainLeft" :src="item.thum_image" mode=""></image>
        <view class="mainRight">
          <view class="name u-line-2">
            {{ item.goods_name }}
          </view>
          <template v-if="typeState === 2">
            <view class="fun">
              {{ item.service_type === 1 ? '上门' : '到店' }}
            </view>
          </template>

          <view class="priceNum" :class="{ marTOp: typeState === 1 || typeState === 3 || typeState === 4 }">
            <text>¥{{ item.goods_price }}</text>
            <template v-if="typeState === 1 || typeState === 3 || typeState === 4">
              <view>
                <image style="display: inline-block; width: 20rpx; height: 20rpx; margin-right: 10rpx" src="../../static/close.png" mode=""></image>
                <text>️{{ item.goods_num }}</text>
              </view>
            </template>
          </view>
        </view>
      </view>
      <view class="goodCard-footer">
        <text style="color: rgba(0, 0, 0, 0.8)">实付款:</text>
        <text>￥{{ item.pay_price }}</text>
      </view>
    </view>

    <!-- 薅羊毛专区 -->
    <template v-if="typeState === 3">
      <view class="card">
        <view class="serveTitle">薅羊毛服务</view>
        <view v-for="item in woolServeList" :key="item.id">
          <view class="serveItemTitle">
            {{ item.server_name }}
          </view>
          <view class="serveItemRow flexJ" v-for="(item2, index2) in item.merchant_list" :key="item2.id">
            <view class="serveItemRow-left flexA">
              <image src="http://qiniu.suboshimuying.cn/static/order/ic-shop@2x.png" mode=""></image>
              <text>{{ item2.name }}</text>
            </view>
            <view class="serveItemRow-right" @click="checkClick(item, item2.id, index2)">
              <image class="check" src="http://qiniu.suboshimuying.cn/static/cart/check.png" v-if="item.merCheckId.includes(item2.id)"></image>
              <image class="check" src="http://qiniu.suboshimuying.cn/static/order/icon24@2x.png" v-else></image>
            </view>
          </view>
        </view>
      </view>

      <view class="remarksCard card">
        <view class="remarksCard-row">
          <text>取货方式</text>
          <view class="rightTabs">
            <text :class="{ active: 2 === server_type }" @click="server_type = 2">去门店自提</text>
            <text :class="{ active: 1 === server_type }" @click="server_type = 1">商家送货上门</text>
          </view>
        </view>
        <view class="remarksCard-row">
          <text>备注</text>
          <view class="ipt">
            <input type="text" placeholder="在此处给商家留言" v-model="remark" />
          </view>
        </view>
      </view>
    </template>

    <!-- 本地服务 -->
    <template v-if="typeState === 2">
      <view class="remarksCard card">
        <template v-if="orderData.goodslist[0].service_type === 1">
          <view class="remarksCard-row" style="margin-top: 0">
            <text>服务人员</text>
            <view class="ipt">
              {{ orderData.goodslist[0].call_pel }}
            </view>
          </view>
        </template>

        <view class="remarksCard-row">
          <text>服务时间</text>
          <view class="ipt flex" @click="serveClick">
            <input type="text" disabled placeholder="请选择服务开始时间" v-model="serve.serveTimeValue" />
            <image src="http://qiniu.suboshimuying.cn/static/order/ic-arrow-more@2x.png" mode=""></image>
          </view>
        </view>
        <!-- <view class="remarksCard-row">
					<text>服务时间</text>
					<view class="ipt">请选择服务结束时间
						<image src="http://qiniu.suboshimuying.cn/static/order/ic-arrow-more@2x.png" mode=""></image>
					</view>
				</view> -->
        <view class="remarksCard-row">
          <text>备注</text>
          <view class="ipt">
            <input type="text" placeholder="在此处给商家留言" v-model="remark" />
          </view>
        </view>
      </view>
    </template>

    <!-- 本地热卖 -->
    <template v-if="typeState === 1 || typeState === 4">
      <view class="remarksCard card">
        <view class="remarksCard-row" style="margin-top: 0">
          <text>备注</text>
          <view class="ipt flex">
            <input type="text" placeholder="在此处给商家留言" v-model="remark" />
          </view>
        </view>
      </view>
    </template>

    <view class="fixedBox">
      <view class="fixedBox-left">
        <template v-if="typeState === 1 || typeState === 4">
          <text style="color: #000; margin-right: 10rpx">共计:</text>
          <text>¥{{ orderData.total_price }}</text>
        </template>
      </view>
      <view class="fixedBox-right" @click="payment">支付</view>
    </view>
    <template v-if="typeState === 3">
      <DiscernPopup :vailType="orderData.goodslist[0].vail_type" @DiscernSubData="DiscernCallback" />
    </template>
  </view>
</template>

<script>
import DiscernPopup from '@/components/DiscernPopup/DiscernPopup.vue'
export default {
  data() {
    return {
      server_type: 1, //取货方式 1=上门,2=到店
      typeState: 0, //订单状态 == 一级分类ID
      flag: true,
      orderData: {}, //订单信息
      defaultRess: {}, //地址信息（初始是默认地址）
      remark: '', //订单备注
      cardIds: '', //购物车id  ，拼接
      serve: {
        serveTimeValue: '', //服务时间（展示）
        server_start_time: '', // 传值（开始）
        server_end_time: '' //传值(结束)
      },
      woolServeList: [], // 薅羊毛增选服务列表
      discernSubData: {} // 识别提交的数据
    }
  },
  components: {
    DiscernPopup
  },
  onLoad(option) {
    // type:一级分类ID   id：商品ID  num：下单数量   flag: true商品详情 falsg购物车

    this.typeState = Number(option.type)

    this.flag = option.flag
    if (option.flag == 'true') {
      //单个商品下单
      this.buydata(option.id, option.num)
      // 获取薅羊毛增选服务
      if (this.typeState === 3) {
        this.getgiveServer(option.id)
      }
    } else {
      //购物车结算
      this.cardIds = option.cardIds
      this.cartClose(option.cardIds)
    }
    // console.log(option);
    // console.log(uni.getStorageSync('fxuserId'));
    this.getDefaultRess() //收货地址
  },
  onShow() {},
  methods: {
    // 跳转
    toUrl(url) {
      uni.navigateTo({
        url
      })
    },
    // 地址点击
    ressClick() {
      uni.navigateTo({
        url: `/subPages/addressList/addressList?type=${false}&id=${this.defaultRess.id}`,
        events: {
          orderAreaBack: data => {
            this.defaultRess = data
            // console.log(data);
          }
        }
      })
    },
    // 服务时间选择
    serveClick() {
      uni.navigateTo({
        url: `/subPages/optionsChange/optionsChange?type=${1}&userType=${2}&value=${this.serve.serveTimeValue}&timeList=${JSON.stringify(this.orderData.goodslist[0].server_time)}`,
        events: {
          timeBack: data => {
            // 单选
            let arr1 = data[0].time.split(' ') //年
            let arr2 = arr1[1].split('-') // 0:开始  1:结束
            // console.log(arr1)
            // console.log(arr2)

            this.serve.serveTimeValue = data[0].time
            this.serve.server_start_time = arr1[0] + ' ' + arr2[0]
            this.serve.server_end_time = arr1[0] + ' ' + arr2[1]
          }
        }
      })
    },
    // 获取单个商品订单信息
    async buydata(id, num) {
      let res = await this.$api.buydata({
        id,
        num
      })
      this.orderData = res.data
      // console.log(res);
    },
    // 识别组件回调
    DiscernCallback(e) {
      this.discernSubData = e
      console.log(e)
    },
    // 支付点击
    async payment() {
      // 判断是否有无地址
      if (this.defaultRess.id) {
        // 分类操作
        switch (this.typeState) {
          case 2:
            //本地服务
            // 判断是否选择服务时间
            if (this.serve.serveTimeValue) {
              let res = await this.$api.goodsPay({
                goods_id: this.orderData.goodslist[0].goods_id, //	商品id
                num: 1, //购买的数量（服务订单默认位1就行）
                address_id: this.defaultRess.id, //收获地址id
                server_start_time: this.serve.server_start_time, //服务开始时间（仅服务订单填写）
                server_end_time: this.serve.server_end_time, //服务结束时间（仅服务订单填写）
                // server_type: this.server_type, //1=上门,2=到店 （仅服务订单填写）
                fxuser_id: uni.getStorageSync('fxuserId'), //分销用户的id
                remark: this.remark //订单备注
              })
              if (res.code === 1) {
                this.paymentCallBack(res.data)
              } else {
                this.$u.toast(res.msg)
              }
            } else {
              this.$u.toast('请选择服务时间')
            }

            break
          case 3:
            // 薅羊毛 - (orderData.goodslist里面只有一个)
            // 薅羊毛服务选择的服务和商家（只有薅羊毛专区才有）
            let arr = []
            let woolServeArr = []

            this.woolServeList.forEach((item, index) => {
              // 判断必选服务是否选择商家
              if (!item.merCheckId.length && item.is_bx == '1') {
                this.$u.toast(`请选择${item.server_name}服务商家`)
                return
              }
              // 整理选择服务商家数据
              // if (item.is_bx == '0') {
              arr = item.merCheckId.map(mer_id => ({ id: item.id, mer_id }))
              arr.length && woolServeArr.push(...arr)
              // }
            })
            let merCheckAllFlag = true
            this.woolServeList.forEach(item => {
              if (item.is_bx == '1' && !item.merCheckId.length) {
                merCheckAllFlag = false
              }
            })
            console.log(merCheckAllFlag)
            if (merCheckAllFlag) {
              let { code, data, msg } = await this.$api.goodsPay({
                goods_id: this.orderData.goodslist[0].goods_id, //	商品id
                num: this.orderData.goodslist[0].goods_num, //购买的数量（服务订单默认位1就行）
                address_id: this.defaultRess.id, //收获地址id
                // server_start_time: 1, //服务开始时间（仅服务订单填写）
                // server_end_time: 2, //服务结束时间（仅服务订单填写）
                server_type: this.server_type, //1=上门,2=到店 （仅服务订单填写）
                fxuser_id: uni.getStorageSync('fxuserId'), //分销用户的id
                remark: this.remark, //订单备注
                give_server_ids: JSON.stringify(woolServeArr), //薅羊毛选的服务
                ...this.discernSubData
              })

              if (code === 1) {
                if (data.is_buy === 1) {
                  // 属于0元购商品直接下单成功
                  this.$u.toast(msg)
                  // this.$u.toast('下单成功')
                } else {
                  // 调起支付
                  this.paymentCallBack(data)
                }
              } else {
                this.$u.toast(msg)
              }
            }

            return
            break
          default:
            if (this.flag == 'true') {
              //单个商品下单
              let { code, data, msg } = await this.$api.goodsPay({
                goods_id: this.orderData.goodslist[0].goods_id, //	商品id
                num: this.orderData.goodslist[0].goods_num, //购买的数量（服务订单默认位1就行）
                address_id: this.defaultRess.id, //收获地址id
                // server_start_time: null, //服务开始时间（仅服务订单填写）
                // server_end_time: null, //服务结束时间（仅服务订单填写）
                // server_type: null, //1=上门,2=到店 （仅服务订单填写）
                fxuser_id: uni.getStorageSync('fxuserId'), //分销用户的id
                remark: this.remark //订单备注
              })
              if (code === 1) {
                this.paymentCallBack(data)
              } else {
                this.$u.toast(msg)
              }
            } else {
              //购物车结算
              // console.log('购物车结算');
              let { code, data, msg } = await this.$api.cartPay({
                cart_ids: this.cardIds, //购物车ID，多个英文逗号隔开
                address_id: this.defaultRess.id, //地址ID
                remark: this.remark //备注
              })
              if (code === 1) {
                this.paymentCallBack(data)
              } else {
                this.$u.toast(msg)
              }
            }
            break
        }
      } else {
        this.$u.toast('暂无收货地址，请先新建收货地址')
        setTimeout(() => {
          uni.navigateTo({
            url: '/subPages/addressList/addressList?type=false',
            events: {
              orderAreaBack: data => {
                this.defaultRess = data
                // console.log(data);
              }
            }
          })
        }, 1500)
      }
    },
    // 获取购物结算订单信息
    async cartClose(cart_ids) {
      let res = await this.$api.cartClose({
        cart_ids //购物车ID，多个英文逗号隔开
      })
      this.orderData = res.data
      // console.log(res);
    },
    // 微信支付
    paymentCallBack(data) {
      let that = this
      uni.requestPayment({
        provider: 'wxpay', // 服务提提供商
        timeStamp: data.timeStamp, // 时间戳
        nonceStr: data.nonceStr, // 随机字符串
        package: data.package,
        signType: data.signType, // 签名算法
        paySign: data.paySign, // 签名
        success(res) {
          //支付成功回调
          that.$u.toast('支付成功')
          setTimeout(() => {
            uni.navigateBack()
          }, 1000)
        },
        fail() {
          //支付失败回调
          that.$u.toast('已取消支付')
        }
      })
    },
    // 获取默认收货地址
    async getDefaultRess() {
      let res = await this.$api.getDefaultRess()
      if (res.data) {
        this.defaultRess = res.data
      } else {
        this.$u.toast('暂无收货地址，请先新建收货地址')
      }
      // console.log(res);
    },
    //获取薅羊毛增选服务
    async getgiveServer(id) {
      let res = await this.$api.getgiveServerList({
        id
      })
      res.data.forEach(item => {
        // 用于存储 该服务下被选中的商家ID（单选）
        this.$set(item, 'merCheckId', [])
      })
      this.woolServeList = res.data
      // console.log(res);
    },
    // 增选服务点击
    checkClick(parent, id, index2) {
      // this.woolServeList.forEach(item => item.is_bx == '0' item.merCheckId.splice(0))

      if (parent.merCheckId.includes(id)) {
        parent.merCheckId.splice(
          parent.merCheckId.findIndex(item => item == id),
          1
        )
      } else parent.merCheckId.push(id)
    }
  }
}
</script>

<style>
page {
  box-sizing: border-box;
  padding: 0 0 188rpx;
}
</style>
<style lang="scss" scoped>
.cityCard {
  display: flex;
  justify-content: space-between;
  align-items: center;

  image {
    margin: 0 8rpx;
    width: 32rpx;
    height: 32rpx;
    vertical-align: middle;
  }

  &-center {
    flex: 1;
    color: rgba(0, 0, 0, 0.8);
    font-size: 28rpx;
    font-weight: 500;
  }
}

.goodCard {
  &-title {
    width: 100%;
    height: 34rpx;
    line-height: 34rpx;
    color: rgba(0, 0, 0, 0.8);
    font-size: 26rpx;
    font-weight: 400;
    font-family: 'PingFang SC';

    image {
      margin-right: 8rpx;
      vertical-align: middle;
      width: 34rpx;
      height: 34rpx;
    }
  }

  &-main {
    margin-top: 20rpx;
    display: flex;
    justify-content: space-between;
    box-sizing: border-box;
    padding-bottom: 30rpx;
    border-bottom: 1rpx solid rgba(171, 171, 171, 0.2);

    .mainLeft {
      width: 180rpx;
      height: 180rpx;
    }

    .mainRight {
      flex: 1;
      margin-left: 24rpx;
      font-weight: 500;
      text-align: left;
      line-height: 40rpx;

      .name {
        height: 88rpx;
        line-height: 44rpx;

        color: rgba(0, 0, 0, 0.8);
        font-size: 26rpx;
      }

      .priceNum {
        display: flex;
        justify-content: space-between;
        align-items: center;
        color: rgba(0, 0, 0, 0.8);
        font-size: 26rpx;
        font-weight: 400;
      }

      .marTOp {
        margin-top: 55rpx;
      }

      .fun {
        margin-top: 10rpx;
        width: 64rpx;
        height: 36rpx;
        line-height: 36rpx;
        border-radius: 8rpx;
        text-align: center;
        background: rgba(236, 237, 254, 1);
        color: $boxBg;
        font-size: 20rpx;
        font-weight: 500;
      }
    }
  }

  &-footer {
    margin-top: 18rpx;
    text-align: right;
    height: 40rpx;
    line-height: 40rpx;
    color: $priceText;
    font-size: 28rpx;
    font-weight: 400;
  }
}

.remarksCard {
  &-row {
    margin-top: 26rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 50rpx;
    color: rgba(0, 0, 0, 0.8);
    font-size: 26rpx;
    font-weight: 400;
    line-height: 40rpx;

    .rightTabs {
      text {
        margin-left: 8rpx;
        box-sizing: border-box;
        padding: 10rpx 16rpx;
        border-radius: 12rpx;
        background: rgba(240, 242, 245, 1);
        color: rgba(0, 0, 0, 0.8);
        font-size: 24rpx;
        font-weight: 400;
      }

      .active {
        background: $boxBg;
        color: #ffffff;
      }
    }

    .ipt {
      flex: 1;
      margin-left: 20rpx;
      text-align: right;
      // display: flex;
      // align-items: center;

      input {
        flex: 1;
        display: inline-block;
        text-align: right;
      }

      image {
        display: inline-block;
        width: 16rpx;
        height: 32rpx;
        vertical-align: middle;
        margin-left: 10rpx;
      }
    }
  }
}

.fixedBox {
  z-index: 99;
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 188rpx;
  background-color: #fff;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-sizing: border-box;
  padding: 0 32rpx 68rpx;

  &-left {
    color: $priceText;
  }

  &-right {
    width: 236rpx;
    height: 80rpx;
    border-radius: 80rpx;
    background: linear-gradient(131.2deg, rgba(179, 142, 255, 1) 0%, rgba(130, 111, 255, 1) 100%);
    line-height: 80rpx;
    text-align: center;
    color: rgba(255, 255, 255, 1);
    font-size: 28rpx;
    font-weight: 600;
  }
}

.flex {
  display: flex;
  align-items: center;
}

.serveTitle {
  color: $textColor;
  font-size: 30rpx;
}

.serveItemTitle {
}

.serveItemRow {
  color: #000;
  font-size: 26rpx;

  &-left {
    box-sizing: border-box;
    padding-left: 32rpx;
    flex: 1;

    image {
      margin-right: 8rpx;
      width: 34rpx;
      height: 34rpx;
    }
  }

  &-right {
    .check {
      margin-right: 22rpx;
      width: 36rpx;
      height: 36rpx;
    }
  }
}
</style>
